package com.thunisoft.converter.font;

import java.io.File;
import java.io.IOException;

import org.apache.fontbox.ttf.RAFDataStream;
import org.apache.fontbox.ttf.TTFDataStream;
import org.apache.fop.fonts.truetype.FontFileReader;

import com.thunisoft.converter.font.ttc.TTCHeader;
import com.thunisoft.converter.font.ttc.TrueTypeCollection;

/**
 * A TrueType Collection file parser
 * 
 * @author weijx
 * @version 1.0 2013-04-13
 */
public class TTCParser {

    /**
     * Parse a file and get a true type font.
     * 
     * @param ttfFile
     *            The TTF file.
     * @throws IOException
     *             If there is an error parsing the true type font.
     */
    public TrueTypeCollection parseTTC(File ttcFile) throws IOException {
        RAFDataStream raf = new RAFDataStream(ttcFile, "r");
        return parseTTC(raf);
    }

    /**
     * Parse a file and get a true type font.
     * 
     * @param raf
     *            The TTF file.
     * @return A true type font.
     * @throws IOException
     *             If there is an error parsing the true type font.
     */
    public TrueTypeCollection parseTTC(TTFDataStream raf) throws IOException {
        TrueTypeCollection fontCollection = new TrueTypeCollection();

        // parse TTC Header
        TTCHeader header = new TTCHeader();
        header.setTTCTag(raf.readString(4));
        header.setVersion(raf.read32Fixed());
        header.setNumFonts(raf.readUnsignedInt());
        fontCollection.setHeader(header);

        return fontCollection;
    }

    public static TTCHeader parserTTCHeader(FontFileReader reader) throws IOException {
        reader.seekSet(0);
        TTCHeader header = new TTCHeader();
        header.setTTCTag(reader.readTTFString(4));
        header.setVersion(read32Fixed(reader));
        header.setNumFonts(reader.readTTFLong());
        long[] offsetTable = new long[(int) header.getNumFonts()];
        for (int i = 0; i < offsetTable.length; i++) {
            offsetTable[i] = reader.readTTFULong();
        }
        header.setOffsetTable(offsetTable);
        return header;
    }

    public static float read32Fixed(FontFileReader reader) throws IOException {
        float retval = 0;
        retval = reader.readTTFShort();
        retval += (reader.readTTFUShort() / 65536.0);
        return retval;
    }
}
